#include "widget.h"
#include "ui_widget.h"


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    m_timer = new QTimer(this);
    m_elapTimer = new QElapsedTimer;

    connect(m_timer, &QTimer::timeout, this,  &Widget::HandelTimeout);
}

Widget::~Widget()
{
    delete m_elapTimer;
    delete ui;
}

void Widget::on_btnStart_clicked()
{
    m_timer->setInterval(ui->spinBoxIntv->value());
    m_timer->setSingleShot(ui->radioOneShot->isChecked());
    if(ui->radioCoarse->isChecked())
    {
        m_timer->setTimerType(Qt::TimerType::CoarseTimer);
    }
    else if(ui->radioVeryCoarse->isChecked())
    {
        m_timer->setTimerType(Qt::TimerType::VeryCoarseTimer);
    }
    else
    {
        m_timer->setTimerType(Qt::TimerType::PreciseTimer);
    }

    m_timer->start();
    m_elapTimer->start();
    ui->labElapsedTime->clear();
    ui->btnStart->setEnabled(false);
    ui->btnOneShot->setEnabled(false);
    ui->btnStop->setEnabled(true);
}

void Widget::HandelTimeout()
{
    QTime time = QTime::currentTime();
    ui->LCDHour->display(time.hour());
    ui->LCDMin->display(time.minute());
    ui->LCDSec->display(time.second());

    if(m_timer->isSingleShot())
    {
        ShowEplResult();

        ui->btnStart->setEnabled(true);
        ui->btnOneShot->setEnabled(true);
        ui->btnStop->setEnabled(false);
    }
}

void Widget::on_btnStop_clicked()
{
    m_timer->stop();
    ShowEplResult();

    ui->btnStart->setEnabled(true);
    ui->btnOneShot->setEnabled(true);
    ui->btnStop->setEnabled(false);
}

void Widget::ShowEplResult()
{
    int tmMesc = m_elapTimer->elapsed();
    int msec = tmMesc % 1000;
    int sec = tmMesc / 1000;
    ui->labElapsedTime->setText(QString("流逝的时间： %1s, %2ms").arg(sec).arg(msec));
}

void Widget::on_btnOneShot_clicked()
{
    m_elapTimer->restart();
    ui->labElapsedTime->clear();
    QTimer::singleShot(ui->spinBoxIntv->value(), this, &Widget::HandelOneshoot);
    ui->btnStart->setEnabled(true);
    ui->btnOneShot->setEnabled(true);
    ui->btnStop->setEnabled(false);
}

void Widget::HandelOneshoot()
{
    QTime time = QTime::currentTime();
    ui->LCDHour->display(time.hour());
    ui->LCDMin->display(time.minute());
    ui->LCDSec->display(time.second());

    ShowEplResult();
}

